// userModel.js
const pool = require("@/db"); // 引入连接池
const table = require("@/db/table"); // 引入连接池

// 查询所有用户
async function getUsers({ username, status, page_index = 1, page_size = 20 }) {
  return await pool
    .select(
      "id,username,email,avatar,nickname,role_id,dept_id,status,created_time,updated_time"
    )
    .where("username", username, "like", "ifHave")
    .where("status", status, "eq", "ifHave")
    .from(table.USER)
    .queryListWithPaging(page_index, page_size);
}

// 根据ID查询用户
async function getUserById({ id, username }) {
  return await pool
    .select("*")
    .from(table.USER)
    .where("id", id, "eq", "ifHave")
    .where("username", username, "eq", "ifHave")
    .queryRow();
}

// 添加用户
async function addUser(user) {
  const result = await pool
    .insert(table.USER, {
      username: user.username,
      password: user.password,
      avatar: user.avatar,
      email: user.email,
      nickname: user.nickname,
      dept_id: user.dept_id,
      role_id: user.role_id,
      created_time: user.created_time,
      updated_time: user.updated_time,
    })
    .execute();
  return result.insertId;
}

// 更新用户
async function updateUser(id, user) {
  const result = await pool.update(table.USER, user).where("id", id).execute();
  return result.affectedRows > 0;
}

// 删除用户
async function deleteUser(id) {
  const result = await pool.delete(table.USER).where("id", id).execute();
  return result.affectedRows > 0;
}

// 获取用户count
async function getUserCount({ id, username }) {
  return await pool
    .select("count(1)")
    .from(table.USER)
    .where("id", id, "eq", "ifHave")
    .where("username", username, "eq", "ifHave")
    .queryValue();
}

module.exports = {
  getUsers,
  getUserById,
  getUserCount,
  addUser,
  updateUser,
  deleteUser,
};
